package com.wl156.activities;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.wl156.BaseActivity;
import com.wl156.MyApp;
import com.wl156.lite.R;
import com.wl156.activities.publish.NewCarInfo;
import com.wl156.model.Certificate;
import com.wl156.model.User;
import com.wl156.model.WebServiceClient;
import com.wl156.utils.Utils;

public class AddCar extends BaseActivity implements OnClickListener {

	protected static final String TAG = null;
	EditText no;
	EditText owner;
	EditText ownerTel;
	EditText driver;
	EditText driverTel;
	EditText type;
	EditText demand;
	EditText carLength;
	EditText load;
	EditText tonnage;
	EditText oftenRun;

	Button add;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	private boolean isCompany;

	private boolean hasInfo;
	private long carId = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_add_car);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		no = (EditText) findViewById(R.id.no);
		owner = (EditText) findViewById(R.id.owner);
		ownerTel = (EditText) findViewById(R.id.ownerTel);
		driver = (EditText) findViewById(R.id.driver);
		driverTel = (EditText) findViewById(R.id.driverTel);
		type = (EditText) findViewById(R.id.type);
		demand = (EditText) findViewById(R.id.demand);
		carLength = (EditText) findViewById(R.id.carLength);
		load = (EditText) findViewById(R.id.load);
		tonnage = (EditText) findViewById(R.id.tonnage);
		oftenRun = (EditText) findViewById(R.id.oftenRun);

		add = (Button) findViewById(R.id.add);
		add.setOnClickListener(this);

		User user = ((MyApp) getApplication()).getCurrentUser();
		Log.d("NewCarInfo", user.type);
		if (user.type.equals("C")) {
			isCompany = true;
		}

		new AsyncTask<Void, Void, Object>() {
			ProgressDialog mProgressDialog;

			protected void onPreExecute() {
				mProgressDialog = ProgressDialog.show(AddCar.this, "", "加载中");
			};

			protected void onPostExecute(Object result) {
				mProgressDialog.dismiss();

				if (result instanceof Exception) {
					Exception e = (Exception) result;
					e.printStackTrace();
					Toast.makeText(AddCar.this, "获取信息失败，请稍后再试",
							Toast.LENGTH_SHORT).show();
				} else {
					try {
						if (isCompany) {
							final SoapObject cars = (SoapObject) result;
							if(cars.getPropertyCount() > 0) {
								SoapObject so = (SoapObject) cars.getProperty(0);
								if (so.getPropertyCount() == 0) {
									return;
								}
							}
							String[] items = new String[(cars
									.getPropertyCount() >= 1 ? 1 : 0)];
							for (int i = 0; i < (cars.getPropertyCount() >= 1 ? 1
									: 0); i++) {
								SoapObject item = (SoapObject) cars
										.getProperty(i);
								items[i] = String.format("%s, %s", Utils
										.propertyToShow(item.getProperty(1)),
										Utils.propertyToShow(item
												.getProperty(5)));
								Log.d(TAG, "items[i]: " + items[i]);
							}
							AlertDialog.Builder builder = new Builder(
									AddCar.this);
							builder.setTitle("选择车辆");
							builder.setItems(items,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											SoapObject item = (SoapObject) cars
													.getProperty(which);
											no.setText(Utils
													.propertyToShow(item
															.getProperty(1)));
											type.setText(Utils
													.propertyToShow(item
															.getProperty(2)));
											tonnage.setText(Utils
													.propertyToShow(item
															.getProperty(3)));
											carLength.setText(Utils
													.propertyToShow(item
															.getProperty(4)));
											owner.setText(Utils
													.propertyToShow(item
															.getProperty(5)));
											ownerTel.setText(Utils
													.propertyToShow(item
															.getProperty(6)));
											// demand.setText(Utils
											// .propertyToShow(item
											// .getProperty(7)));
											carId = Long.valueOf(Utils
													.propertyToShow(item
															.getProperty(0)));
											hasInfo = true;
											add.setVisibility(View.GONE);
											setTitle("我的车辆信息");
										}
									});
							builder.show();
						} else {
							final SoapObject item = (SoapObject) result;
//							if(item.getPropertyCount() > 0) {
//								SoapObject so = (SoapObject) item.getProperty(0);
//								if (so.getPropertyCount() == 0) {
//									return;
//								}
//							}
							no.setText(Utils.propertyToShow(item.getProperty(0)));
							type.setText(Utils.propertyToShow(item
									.getProperty(1)));
							tonnage.setText(Utils.propertyToShow(item
									.getProperty(2)));
							carLength.setText(Utils.propertyToShow(item
									.getProperty(3)));
							owner.setText(Utils.propertyToShow(item
									.getProperty(4)));
							ownerTel.setText(Utils.propertyToShow(item
									.getProperty(5)));
							// demand.setText(Utils.propertyToShow(item
							// .getProperty(7)));
//							carId = Long.valueOf(Utils.propertyToShow(item
//									.getProperty(0)));
							hasInfo = true;
							add.setVisibility(View.GONE);
							setTitle("我的车辆信息");
						}
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(AddCar.this, "获取信息失败，请稍后再试",
								Toast.LENGTH_SHORT).show();
					}
				}
			};

			@Override
			protected Object doInBackground(Void... params) {

				try {
					if (isCompany) {
						return mWebServiceClient.company_getMyTruck(
								mCertificate, "", "", "");
					} else {
						return mWebServiceClient.driverGetMyTruck(mCertificate);
					}
				} catch (IOException e) {
					e.printStackTrace();
					return e;
				} catch (XmlPullParserException e) {
					e.printStackTrace();
					return e;
				}
			}

		}.execute();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add:
			final String No = no.getText().toString();
			final String Owner = owner.getText().toString();
			final String OwnerTel = ownerTel.getText().toString();
			final String Driver = driver.getText().toString();
			final String DriverTel = driverTel.getText().toString();
			final String Type = type.getText().toString();
			final String Demand = demand.getText().toString();
			final String CarLength = carLength.getText().toString();
			final String Load = load.getText().toString();
			final String Tonnage = tonnage.getText().toString();
			final String oftenRu = oftenRun.getText().toString();

			if (TextUtils.isEmpty(No) || TextUtils.isEmpty(Owner)
					|| TextUtils.isEmpty(OwnerTel) || TextUtils.isEmpty(Driver)
					|| TextUtils.isEmpty(DriverTel) || TextUtils.isEmpty(Type)
					|| TextUtils.isEmpty(Demand)
					|| TextUtils.isEmpty(CarLength) || TextUtils.isEmpty(Load)) {
				Toast.makeText(AddCar.this, "请填写相应的字段", Toast.LENGTH_LONG)
						.show();
				return;
			}

			new AsyncTask<Void, Void, Object>() {

				@Override
				protected void onPostExecute(Object result) {
					if (result instanceof Exception) {
						Exception e = (Exception) result;
						e.printStackTrace();

						Toast.makeText(AddCar.this, "添加失败，请稍候再试",
								Toast.LENGTH_LONG).show();
					} else {
						if (result instanceof SoapPrimitive) {
							SoapPrimitive sp = (SoapPrimitive) result;
							Toast.makeText(AddCar.this, sp.toString(),
									Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(AddCar.this, "添加成功",
									Toast.LENGTH_LONG).show();
							setResult(Activity.RESULT_OK);
							finish();
						}
					}
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						if (hasInfo) {
							return mWebServiceClient.common_UpdateMyCar(
									mCertificate, carId, No, Owner, OwnerTel,
									Driver, DriverTel, Type, Demand, Float
											.valueOf(CarLength), Float
											.valueOf(Load), 0, oftenRun
											.getText().toString());
						} else {
							return mWebServiceClient.common_AddCarInfo(
									mCertificate, No, Owner, OwnerTel, Driver,
									DriverTel, Type, Demand,
									Float.valueOf(CarLength),
									Float.valueOf(Load),
									Float.valueOf(Tonnage), oftenRu);
						}

					} catch (NumberFormatException e) {
						return e;
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					}
				}
			}.execute();

			break;
		default:
			break;
		}
	}
}
